<template>
  <div>
    <canvas ref="canvasRef" width="800" height="600"></canvas>
    <button @click="zoomIn">放大</button>
    <button @click="zoomOut">缩小</button>
    <!-- 添加定位按钮 -->
    <button @click="locate">定位</button>
    <div>
      <div v-for="(item, index) in newPoints" :key="index">
        <div ref="externalPointRef" draggable="true" @dragstart="handleDragStart($event, index)" @dragend="handleDragEnd(index)">{{ item.name }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import mapImage from '@/assets/images/map/map.jpg';
import point from '@/assets/images/map/point.png';
import point2 from '@/assets/images/map/pointBlue.png'; // 新增第二张点图片
import deleteIcon from '@/assets/images/map/deleteIcon.png'; // 新增删除图标

const canvasRef = ref(null);
const externalPointRef = ref(null);
const scale = ref(1);
const MIN_SCALE = 0.1;
const MAX_SCALE = 5;
const ZOOM_STEP = 0.05;
// 图片
const image = new Image();
image.src = mapImage;
const imagePoint = new Image();
imagePoint.src = point;
const imagePoint2 = new Image(); // 新增第二张点图片对象
imagePoint2.src = point2;
const deleteImage = new Image();
deleteImage.src = deleteIcon;
// 待新增点位列表
const newPoints = ref([
  { id: 3, name: '第三个摄像头', radius: 5, isSelected: false },
  { id: 4, name: '第四个摄像头', radius: 5, isSelected: false },
  { id: 5, name: '第五个摄像头', radius: 5, isSelected: false },
]);
// 新增变量用于记录图片的偏移量
const offsetX = ref(0);
const offsetY = ref(0);
// 记录鼠标按下时的位置
const startX = ref(0);
const startY = ref(0);
// 记录鼠标是否按下
const isDragging = ref(false);
// 记录点是否被拖动
const isPointDragging = ref(false);
// 记录当前拖动点的 id
const draggingPointId = ref(null);
// 记录外部点是否正在拖动
const isExternalPointDragging = ref(false);

// 定义要绘制的点的数组，每个点包含 id、x、y 坐标、半径和是否选中
const points = ref([
  { id: 1, name: '第一个摄像头', x: 20, y: 30, radius: 5, isSelected: false },
  { id: 2, name: '第二个摄像头', x: 50, y: 80, radius: 5, isSelected: false },
  // 可以继续添加更多的点
]);

const drawImage = () => {
  const canvas = canvasRef.value;
  const ctx = canvas.getContext('2d');
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.save();
  ctx.scale(scale.value, scale.value);
  ctx.translate(offsetX.value / scale.value, offsetY.value / scale.value);
  ctx.drawImage(image, 0, 0);

  // 绘制所有点
  points.value.forEach(point => {
    const currentImage = point.isSelected ? imagePoint2 : imagePoint;
    ctx.beginPath();
    ctx.drawImage(currentImage, point.x - 13.5, point.y - 26, 27, 52);
    ctx.fill();

    if (point.isSelected) {
      // 绘制选中框
      const boxWidth = 100;
      const boxHeight = 20;
      const boxX = point.x - boxWidth / 2;
      const boxY = point.y - 26 - boxHeight - 5;

      ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
      ctx.fillRect(boxX, boxY, boxWidth, boxHeight);

      // 绘制名字
      ctx.fillStyle = 'black';
      ctx.font = '12px Arial';
      ctx.fillText(point.name, boxX + 5, boxY + 15);

      // 绘制删除图标
      const iconSize = 16;
      const iconX = boxX + boxWidth - iconSize - 5;
      const iconY = boxY + (boxHeight - iconSize) / 2;
      ctx.drawImage(deleteImage, iconX, iconY, iconSize, iconSize);
    }
  });

  ctx.restore();
};

const zoomIn = () => {
  if (scale.value < MAX_SCALE) {
    scale.value += ZOOM_STEP;
    drawImage();
  }
};

const zoomOut = () => {
  if (scale.value > MIN_SCALE) {
    scale.value -= ZOOM_STEP;
    drawImage();
  }
};

const handleWheel = (event) => {
  event.preventDefault();
  const delta = event.deltaY > 0 ? -ZOOM_STEP : ZOOM_STEP;
  const newScale = scale.value + delta;
  if (newScale >= MIN_SCALE && newScale <= MAX_SCALE) {
    scale.value = newScale;
    drawImage();
  }
};

// 处理鼠标按下事件
const handleMouseDown = (event) => {
  const canvas = canvasRef.value;
  const rect = canvas.getBoundingClientRect();
  const clickX = (event.clientX - rect.left - offsetX.value) / scale.value;
  const clickY = (event.clientY - rect.top - offsetY.value) / scale.value;

  let isPointClicked = false;
  points.value.forEach(point => {
    const imageX = point.x - 13.5;
    const imageY = point.y - 26;
    const imageWidth = 27;
    const imageHeight = 52;

    if (
      clickX >= imageX &&
      clickX <= imageX + imageWidth &&
      clickY >= imageY &&
      clickY <= imageY + imageHeight
    ) {
      isPointDragging.value = true;
      draggingPointId.value = point.id;
      startX.value = clickX;
      startY.value = clickY;
      isPointClicked = true;
    }

    // 检查是否点击了删除图标
    if (point.isSelected) {
      const boxWidth = 100;
      const boxHeight = 20;
      const boxX = point.x - boxWidth / 2;
      const boxY = point.y - 26 - boxHeight - 5;
      const iconSize = 16;
      const iconX = boxX + boxWidth - iconSize - 5;
      const iconY = boxY + (boxHeight - iconSize) / 2;

      if (
        clickX >= iconX &&
        clickX <= iconX + iconSize &&
        clickY >= iconY &&
        clickY <= iconY + iconSize
      ) {
        // 删除点
        points.value = points.value.filter(p => p.id !== point.id);
        drawImage();
      }
    }
  });

  if (!isPointClicked) {
    // 取消所有点的选中状态
    points.value.forEach(p => p.isSelected = false);
    isDragging.value = true;
    startX.value = event.offsetX;
    startY.value = event.offsetY;
  }

  drawImage();
};

// 处理鼠标移动事件
const handleMouseMove = (event) => {
  const canvas = canvasRef.value;
  const rect = canvas.getBoundingClientRect();
  const mouseX = (event.clientX - rect.left - offsetX.value) / scale.value;
  const mouseY = (event.clientY - rect.top - offsetY.value) / scale.value;

  let isOverPoint = false;
  points.value.forEach(point => {
    const imageX = point.x - 13.5;
    const imageY = point.y - 26;
    const imageWidth = 27;
    const imageHeight = 52;

    if (
      mouseX >= imageX &&
      mouseX <= imageX + imageWidth &&
      mouseY >= imageY &&
      mouseY <= imageY + imageHeight
    ) {
      isOverPoint = true;
    }
  });

  if (isOverPoint) {
    canvas.style.cursor = 'pointer';
  } else {
    canvas.style.cursor = 'default';
  }

  if (isPointDragging.value) {
    const dx = mouseX - startX.value;
    const dy = mouseY - startY.value;

    const currentPoint = points.value.find(point => point.id === draggingPointId.value);
    if (currentPoint) {
      // 计算新的点位置
      let newX = currentPoint.x + dx;
      let newY = currentPoint.y + dy;

      // 限制点的位置在图片范围内
      newX = Math.max(13.5, Math.min(newX, image.width - 13.5));
      newY = Math.max(26, Math.min(newY, image.height - 26));

      currentPoint.x = newX;
      currentPoint.y = newY;

      startX.value = mouseX;
      startY.value = mouseY;

      drawImage();
      console.log(`点 ${draggingPointId.value} 拖动到的位置相对于图片: (${newX}, ${newY})`);
    }
  } else if (isDragging.value) {
    const dx = event.offsetX - startX.value;
    const dy = event.offsetY - startY.value;
    offsetX.value += dx;
    offsetY.value += dy;
    startX.value = event.offsetX;
    startY.value = event.offsetY;
    drawImage();
  }
};

// 处理鼠标松开事件
const handleMouseUp = () => {
  isDragging.value = false;
  isPointDragging.value = false;
  draggingPointId.value = null;
};

// 处理点击事件
const handleClick = (event) => {
  const canvas = canvasRef.value;
  const rect = canvas.getBoundingClientRect();
  const clickX = (event.clientX - rect.left - offsetX.value) / scale.value;
  const clickY = (event.clientY - rect.top - offsetY.value) / scale.value;

  // 取消所有点的选中状态
  points.value.forEach(p => p.isSelected = false);

  points.value.forEach(point => {
    const imageX = point.x - 13.5;
    const imageY = point.y - 26;
    const imageWidth = 27;
    const imageHeight = 52;

    if (
      clickX >= imageX &&
      clickX <= imageX + imageWidth &&
      clickY >= imageY &&
      clickY <= imageY + imageHeight
    ) {
      console.log(`点 ${point.id} 被点击了！`);
      // 选中点
      point.isSelected = true;
      drawImage();
    }
  });
};

// 处理外部点拖动开始事件
const handleDragStart = (event, index) => {
  isExternalPointDragging.value = true;
  // 设置拖动时的自定义图片
  event.dataTransfer.setDragImage(imagePoint, 13.5, 26);
};

// 处理外部点拖动结束事件
const handleDragEnd = (index) => {
  const canvas = canvasRef.value;
  const rect = canvas.getBoundingClientRect();
  if (
    event.clientX >= rect.left &&
    event.clientX <= rect.right &&
    event.clientY >= rect.top &&
    event.clientY <= rect.bottom
  ) {
    const clickX = (event.clientX - rect.left - offsetX.value) / scale.value;
    const clickY = (event.clientY - rect.top - offsetY.value) / scale.value;
    const draggedPoint = newPoints.value[index];
    const newPoint = {
      id: draggedPoint.id,
      name: draggedPoint.name,
      x: clickX,
      y: clickY,
      radius: 5,
      isSelected: false
    };
    points.value.push(newPoint);
    drawImage();
    console.log(`新点 ${newPoint.id} 放置在相对于图片的位置: (${clickX}, ${clickY})`);
  }
  isExternalPointDragging.value = false;
};

// 定位函数
const locate = () => {
  const canvas = canvasRef.value;
  // 适当放大，例如放大到 2 倍
  scale.value = 2;
  // 计算图片中心点相对于画布的偏移量
  offsetX.value = (canvas.width / 2 - image.width / 2 * scale.value);
  offsetY.value = (canvas.height / 2 - image.height / 2 * scale.value);
  drawImage();
};

onMounted(() => {
  const canvas = canvasRef.value;
  canvas.addEventListener('wheel', handleWheel);
  canvas.addEventListener('mousedown', handleMouseDown);
  canvas.addEventListener('mousemove', handleMouseMove);
  canvas.addEventListener('mouseup', handleMouseUp);
  canvas.addEventListener('click', handleClick);

  image.onload = () => {
    drawImage();
  };
});
</script>